package com.roger.uia.helper.manager;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.support.test.InstrumentationRegistry;
import android.util.Log;

import java.util.List;

public class Wifi {
    private static final String TAG = "Test" + Wifi.class.getSimpleName();
    private WifiManager wifiManager = (WifiManager) InstrumentationRegistry.getTargetContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    public static Wifi wifi(){ return new Wifi(); }

    public void connectWifi(String targetSsid, String targetPsd, String enc) {
        String ssid = "\"" + targetSsid + "\"";
        String psd = "\"" + targetPsd + "\"";

        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = ssid;
        switch (enc) {
            case "WEP":
                conf.wepKeys[0] = psd;
                conf.wepTxKeyIndex = 0;
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                break;
            case "WPA":
                conf.preSharedKey = psd;
                break;
            case "OPEN":
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }
        wifiManager.addNetwork(conf);
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration i : list) {
            if (i.SSID != null && i.SSID.equals(ssid)) {
                wifiManager.disconnect();
                wifiManager.enableNetwork(i.networkId, true);
                wifiManager.reconnect();
                break;
            }
        }
    }

    public String getWifiSaved() {
        StringBuilder s = new StringBuilder();
        List<WifiConfiguration> wifiConfigs = wifiManager.getConfiguredNetworks();
        if(!String.valueOf(wifiConfigs).equals("[]")){
            for (WifiConfiguration wifiConfig : wifiConfigs) {
                Log.d(TAG,wifiConfig.SSID);
                s.append(wifiConfig.SSID.replaceAll("\"","")).append("\n");
            }
            return String.valueOf(s);
        }
        return "";
    }
}
